<template>
  <div ref="chartContainer" :style="{ height: height, width: width }"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'DeviceStartRateChart',
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    chartData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      chartInstance: null,
      chartContainer: null
    };
  },
  watch: {
    chartData: {
      handler() {
        this.initChart();
      },
      deep: true
    }
  },
  mounted() {
    this.chartContainer = this.$refs.chartContainer;
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    initChart() {
      if (!this.chartContainer) return;
      
      const chartInstance = echarts.init(this.chartContainer);

      // 处理数据，确保有有效的数据
      const dataKeys = Object.keys(this.chartData || {});
      const dataValues = dataKeys.map(key => {
        const value = this.chartData[key];
        return typeof value === 'string' ? parseFloat(value) : value || 0;
      });

      // 如果没有数据，生成默认数据
      const defaultData = this.generateDefaultData();
      const xAxisData = dataKeys.length > 0 ? dataKeys : Object.keys(defaultData);
      const seriesData = dataValues.length > 0 ? dataValues : Object.values(defaultData);

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            if (!params || !params[0]) return '';
            const data = params[0];
            return `${data.name}<br/>${data.marker}设备开动率: ${data.value}%`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
          axisLabel: {
            rotate: 45,
            interval: 0,
            formatter: (value) => {
              // 格式化时间标签，保持显示完整
              return value;
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '开动率(%)',
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '设备开动率',
            type: 'line',
            smooth: true,
            data: seriesData,
            areaStyle: {
              opacity: 0.3
            },
            lineStyle: {
              width: 3
            },
            itemStyle: {
              color: '#1890ff'
            },
            markLine: {
              silent: true,
              data: [
                { yAxis: 60, name: '最低标准', lineStyle: { color: '#ff4d4f' } },
                { yAxis: 80, name: '目标标准', lineStyle: { color: '#52c41a' } }
              ]
            }
          }
        ],
        toolbox: {
          feature: {
            saveAsImage: {
              title: '保存为图片'
            },
            dataZoom: {
              yAxisIndex: 'none'
            },
            restore: {}
          }
        }
      };

      chartInstance.setOption(option);
      this.chartInstance = chartInstance;
    },
    generateDefaultData() {
      // 生成过去24小时的默认数据
      const data = {};
      const now = new Date();
      
      for (let i = 23; i >= 0; i--) {
        const time = new Date(now.getTime() - i * 60 * 60 * 1000);
        const hour = time.getHours().toString().padStart(2, '0');
        const key = `${hour}:00`;
        // 生成一个合理的随机值，模拟真实数据波动
        const baseValue = 65 + Math.sin((23 - i) / 24 * Math.PI) * 15;
        const randomValue = baseValue + (Math.random() - 0.5) * 20;
        data[key] = Number(randomValue.toFixed(2));
      }
      
      return data;
    }
  }
};
</script>